package com.xinqi.modules.sys.gpt.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @version V1.0
 * @Title:
 * @ClassName: com.xinqi.modules.sys.gpt.util.ExecutorConfig.java
 * @Description:
 * @Copyright 星齐科技（云南）有限公司 - Powered By 技术部
 * @author: yyzhen
 * @date: 2023/5/31 20:38
 */
@Configuration
public class ExecutorConfig {

    @Value("${threadPool.corePoolSize}")
    private int corePoolSize;

    @Value("${threadPool.maxPoolSize}")
    private int maxPoolSize;

    @Value("${threadPool.keepAliveSeconds}")
    private int keepAliveSeconds;

    @Value("${threadPool.queueCapacity}")
    private int queueCapacity;

    @Value("${threadPool.namePrefix}")
    private String namePrefix;

    /**
     * 初始化线程池参数
     *
     * @return
     */
    @Bean(value = "taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        taskExecutor.setThreadNamePrefix(namePrefix);
        // 直接在execute方法的调用线程中运行
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        taskExecutor.initialize();
        return taskExecutor;
    }

}
